package com.cn.web;

import com.cn.Utils.MyPageable;
import com.cn.entity.RunLog;
import com.cn.entity.RunLogTime;
import com.cn.service.RunLogService;
import com.cn.utils.StringUtil;
import com.cn.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenyuncong on 2018/8/2.
 */
@RestController
@RequestMapping("runLog")
public class RunLogController {

    @Autowired
    private RunLogService runLogService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("runLogList")
    public List<RunLog>  runLogList() throws Exception {
//        mongoTemplate.
        String sql = "select add_time,all_control_data,customer_name,error_stop,id l_id,ip,mac,mac_run_status,normal_stop,running,the_event,the_time,company_id from run_status  limit 10"  ;
        List<RunLog> list = runLogService.getList(sql, RunLog.class);
        return list;
    }
    /**
     * 用时间做条件
     *
     * @return
     */
    @GetMapping("getRunLogTime")
    public List<RunLogTime> getRunLogTime() throws ParseException {
        Query query = new Query();

//        SimpleDateFormat format =  new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss:SSS" );

        Criteria criteria = new Criteria();
        Long startTime = TimeUtils.strToTime("2018-07-26 00:00:00");
        Long endTime = TimeUtils.strToTime("2018-07-26 23:59:59");
        criteria.andOperator(Criteria.where("the_time_long").gte(startTime).lt(endTime).and("mac").is("00:80:f4:40:a0:61"));
        query.addCriteria(criteria);

        query.skip(0);
        query.limit(10);
//        query.with(Sort.by(
//                Sort.Order.asc("readOrNot"),
//                Sort.Order.desc("sendTime")
//        ));
        List<RunLogTime> list =mongoTemplate.find(query, RunLogTime.class);
        return list;
    }

    @GetMapping("toMongodbBatch")
    public String toMongodbBatch() throws ParseException {

        Query query = new Query();
        Criteria criteria = new Criteria();
        Long startTime = TimeUtils.strToTime("2018-07-25 00:00:00");
        Long endTime = TimeUtils.strToTime("2018-07-26 23:59:59");
        criteria.andOperator(Criteria.where("the_time_long").gte(startTime).lt(endTime));
        query.addCriteria(criteria);
        List<RunLogTime> list =mongoTemplate.find(query, RunLogTime.class);

        List<String> slist = StringUtil.getDateList("2018-01-01 00:00:00", "2019-04-24 00:00:00", "","yyyy-MM-dd");
        slist.forEach(x->{
            try {
                System.out.println(x);
                long sTime = TimeUtils.strToTime(x, "yyyy-MM-dd");
                System.out.println(sTime);
                for(RunLogTime r:list){
                    sTime++;
                    r.setId(null);
                    r.setAdd_time_long(new Date(sTime).getTime());
                    r.setThe_time_long(new Date(sTime).getTime());
                }
                System.out.println(sTime);
                System.out.println();
                fenyeSave(list);

            } catch (ParseException e) {
                e.printStackTrace();
            }
        });



        return null;
    }

    private void fenyeSave( List<RunLogTime> list){
        List<RunLogTime> rList= new ArrayList<>();
        for(int i = 0; i < list.size(); i++){
            rList.add(list.get(i));
            if(i%1000==0){
                mongoTemplate.insertAll(rList);
                rList.clear();
            }
        }
        mongoTemplate.insertAll(rList);
    }

    /**
     * 用时间做条件
     *
     * @return
     */
    @GetMapping("getRunLogDate")
    public List<RunLog> getRunLogDate() throws ParseException {
        Query query = new Query();

//        Calendar calendar = Calendar.getInstance();
//        calendar.set(2018,6,11,15,30,30);
        // 大于等于2018-08-01 小于2018-08-02
        // db.getCollection('runLog').find({ "add_time" : { "$gte" : new Date("2018-08-01"), "$lt" : new Date("2018-08-02") } })
        // 大于等于 2018-08-01 的数据
        // db.getCollection('runLog').find({ "add_time" : { "$gte" : new Date("2018-08-01")},"mac": "00:80:f4:40:a0:61"})


//        Calendar calendar = Calendar.getInstance(); //日历
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, -2);
//        Date todayStart = calendar.getTime();
//        calendar.add(Calendar.DATE, -1);
//        Date endStart = calendar.getTime();


        SimpleDateFormat format =  new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss:SSS" );

        Criteria criteria = new Criteria();
        Date startTime = format.parse("2018-08-01 00:00:00:000");
        Date endTime = format.parse("2018-08-02 00:00:00:000");
        criteria.andOperator(Criteria.where("the_time").gte(startTime ).lt(endTime).and("mac").is("00:80:f4:40:a0:61"));
        query.addCriteria(criteria);

        query.skip(0);
        query.limit(10);
        List<RunLog> list =mongoTemplate.find(query, RunLog.class);
        return list;
    }



    /**
     * 把mysql数据批量进mongodb
     *
     * @throws Exception
     */
    @GetMapping("mysqlToMongoDB")
    public void mysqlToMongoDB() throws Exception {
        String countSql = "select count(1) from run_status ";
        int total = runLogService.count(countSql);
        int num = total % 1000 == 0 ? total / 1000 : (total / 1000) + 1;

        String sql = "";
        List<RunLogTime> rList = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            sql = "select add_time,all_control_data,customer_name,error_stop,id l_id,ip,mac,mac_run_status,normal_stop,running,the_event,the_time,company_id from run_status " + toLimit(1000, i);
            List<RunLog> list = runLogService.getList(sql, RunLog.class);
            list.forEach(x->{
                rList.add(new RunLogTime(x,x.getAdd_time().getTime(),x.getThe_time().getTime()));
            });
            mongoTemplate.insertAll(rList);
            System.out.println(i+" 插入 "+rList.size()+" 完成");
            rList.clear();
            System.out.println("清空集合："+rList.size());
        }
//        runLogService.getList()

    }

    public static String toLimit(Integer pageSize, Integer pageNumber) {
        pageSize = (pageSize == null) ? 10 : pageSize;
        pageNumber = (pageNumber == null || pageNumber <= 0) ? 1 : pageNumber;
        return "limit " + ((pageNumber - 1) * pageSize) + "," + pageSize;
    }


    @GetMapping("mysqlToMongoDB2")
    public void mysqlToMongoDB2() throws Exception {


//        String sql = "select add_time,all_control_data,customer_name,error_stop,id l_id,ip,mac,mac_run_status,normal_stop,running,the_event,the_time,company_id from run_status " ;

        String sql = "select add_time,all_control_data,customer_name,error_stop,id l_id,ip,mac,mac_run_status,normal_stop,running,the_event,the_time,company_id " +
                "from run_status where the_time >= '2018-07-25 00:00:00' and the_time <= '2018-08-02 23:59:59' order by the_time"  ;
        List<RunLogTime> list = runLogService.getList(sql, RunLogTime.class);


        List<String> slist = StringUtil.getDateList("2017-01-02 00:00:00", "2018-06-13 00:00:00", "","yyyyMMdd");

        List<RunLogTime> rList = new ArrayList<>();

        for(String key : slist){
            list.forEach(x->x.setId(null));
            long time = TimeUtils.strToTime(key,"yyyyMMdd");
            int doDay = Integer.parseInt(key);
            System.out.println(doDay);
            for(int i=0;i<list.size();i++){

                list.get(i).setTo_day(doDay);
                list.get(i).setAdd_time_long(time);
                rList.add(list.get(i));
                if(i%1000==0){
                    mongoTemplate.insertAll(rList);
                    rList.clear();
                }
                time++;
            }
            mongoTemplate.insertAll(rList);
            rList.clear();
        }
    }
}
